package com.abe.bathsystem.android;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;

import com.abe.bathsystem.android.v3.MainBathShowActivity;
import com.abe.bathsystem.base.AutoMvpActivity;
import com.abe.bathsystem.base.ManagerTimer;
import com.abe.bathsystem.contract.CommonContract;
import com.abe.bathsystem.contract.presenter.VersionPresenter;
import com.abe.bathsystem.entity.http.HttpVersionEntity;
import com.abe.bathsystem.utils.AudioUtil;
import com.abe.bathsystem.utils.NormalUtils;
import com.abe.bathsystem.widget.dialog.DialogContract;
import com.abe.bathsystem.widget.dialog.VersionDialog;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.ConstantCore;
import com.abe.libcore.utils.normal.FileDownloadUtils;
import com.abe.libcore.utils.normal.NetWorkUtils;
import com.abe.libcore.utils.normal.ToastUtils;
import com.bumptech.glide.Glide;

import net.yet.campusdev.R;

import java.io.File;

import butterknife.BindView;

public class SplashActivity extends AutoMvpActivity implements CommonContract.VersionView {

    @BindView(R.id.fullscreen_content)
    ImageView fullscreenContent;
    private boolean isNeedUpdate = false;
    private boolean isCountDownEnd = false;
    private boolean isGetServerSuccess = false;
    private HttpVersionEntity httpVersionEntity;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initContent() {
        if (AudioUtil.getInstance(this).getMediaVolume() < AudioUtil.getInstance(this).getMediaMaxVolume()) {
            AudioUtil.getInstance(this).setMediaVolume(AudioUtil.getInstance(this).getMediaMaxVolume());
        }
        Glide.with(this).load(R.drawable.icon_welcome).centerCrop().into(fullscreenContent);
        new BaseHandler(Looper.getMainLooper()).sendEmptyMessageDelayed(MSG_START, 1000 * 3);
        if (!NetWorkUtils.isNetConnected(this)) {
            isGetServerSuccess = true;
        } else {
            versionPresenter().checkVersion(false);
        }
    }

    private static final int MSG_START = 0x001;
    private static final int MSG_GOTO = 0x002;
    private static final int MSG_COMPARE = 0x003;
    private static final int APP_TOAST = 0x004;

    protected void localSendEmptyMessage(int what) {
        new BaseHandler(Looper.getMainLooper()).sendEmptyMessage(what);
    }

    protected void localSendMessage(int what, Object object) {
        Message message = new Message();
        message.obj = object;
        message.what = what;
        new BaseHandler(Looper.getMainLooper()).sendMessage(message);
    }

    @Override
    public void onCheckVersion(boolean isSuccess, boolean isAutoUpdate, HttpVersionEntity versionEntity) {
        isGetServerSuccess = true;
        httpVersionEntity = versionEntity;
        if (isSuccess) {
            if (versionEntity != null) {
                int currentCode = NormalUtils.getVersionCode();
                CommonUtils.w("httpVersionEntity:" + currentCode);
                if (currentCode < versionEntity.getVersionCode()) {
                    isNeedUpdate = true;
                }
            }
        }
        if (isCountDownEnd) {
            localSendEmptyMessage(MSG_COMPARE);
        }
    }


    @Override
    public VersionPresenter versionPresenter() {
        return (VersionPresenter) getPresenter(VersionPresenter.class);
    }

    @Override
    public void onFinish(Object type) {
    }

    @Override
    public void onFailure(Object type) {
        isGetServerSuccess = true;
        if (isCountDownEnd) {
            localSendEmptyMessage(MSG_GOTO);
        }
    }

    public class BaseHandler extends Handler {
        BaseHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case APP_TOAST: {
                    if (!TextUtils.isEmpty(msg.obj.toString())) {
                        ToastUtils.show(msg.obj.toString());
                    }
                }
                break;
                case MSG_START: {
                    isCountDownEnd = true;
                    if (isGetServerSuccess) {
                        localSendEmptyMessage(MSG_COMPARE);
                    }
                }
                break;
                case MSG_GOTO: {
                    Bundle bundle = new Bundle();
                    bundle.putString("act", SplashActivity.class.getSimpleName());
                    gotoActivity(MainBathShowActivity.class, bundle);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    SplashActivity.this.finish();
                }
                break;
                case MSG_COMPARE: {
                    if (!isNeedUpdate) {
                        localSendEmptyMessage(MSG_GOTO);
                    } else {
                        if (httpVersionEntity != null) {
                            //展示版本更新弹窗
                            VersionDialog dialog = new VersionDialog(SplashActivity.this, httpVersionEntity);
                            dialog.setListener(new DialogContract.OnUpdateListener() {
                                @Override
                                public void onUpdate(boolean isUpdate, String url) {
                                    if (isUpdate) {
                                        final String apkName = "bath-" + httpVersionEntity.getVersionName() + ".apk";
                                        FileDownloadUtils.get().download(url, "abeframe", apkName, new FileDownloadUtils.OnDownloadListener() {
                                            @Override
                                            public void onDownloadSuccess() {
                                                localSendMessage(APP_TOAST, "下载成功");
                                                boolean isInstall = NormalUtils.installAPK(ConstantCore.FILE_ROOT_PATH + File.separator + apkName);
                                                if (!isInstall) {
                                                    localSendMessage(APP_TOAST, "安装路径错误");
                                                    localSendEmptyMessage(MSG_GOTO);
                                                }
                                            }

                                            @Override
                                            public void onDownloading(int progress) {

                                            }

                                            @Override
                                            public void onDownloadFailed() {
                                                localSendMessage(APP_TOAST, "下载失败");
                                                localSendEmptyMessage(MSG_GOTO);
                                            }
                                        });
                                    } else {
                                        localSendEmptyMessage(MSG_GOTO);
                                    }
                                }
                            });
                            //设置点击外部不消失
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                                @Override
                                public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                                    return keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0;
                                }
                            });
                            dialog.show();
                            new BaseHandler(Looper.getMainLooper()).sendEmptyMessageDelayed(MSG_GOTO, ManagerTimer.autoLockTime());
                        } else {
                            localSendEmptyMessage(MSG_GOTO);
                        }
                    }
                }
                break;
            }
            super.handleMessage(msg);
        }
    }
}
